<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import router from "@/router/index.js";
import {useNavStore} from "@/stores/nav.js";
import {getUsersApi} from "@/api/users.js";

const navStore = useNavStore()
const userList = ref([])

const getUserList = async () => {
  let res = await getUsersApi()
  console.log(res)
}
onMounted(() => {
  // 获取所有用户基本信息
  getUserList()
})

const organizationOptions = [
  {
    value: '河南工业和信息化职业学院',
    label: '河南工业和信息化职业学院',
    children: [
      {
        value: '计算机应用技术',
        label: '计算机应用技术',
        children: [
          {
            value: '2022级',
            label: '2022级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' }
            ]
          },
          {
            value: '2023级',
            label: '2023级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' }
            ]
          },
          {
            value: '2024级',
            label: '2024级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' }
            ]
          },
          {
            value: '2025级',
            label: '2025级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' }
            ]
          }
        ]
      }
    ]
  }
]

const createMockUsers = () =>
    [
      {id: 1,
        name: '李明',
        gender: '男',
        stuId: '20222154521',
        account: 'LM20250902',
        password: '123456',
        contact: '-',
        organization: ['河南工业和信息化职业学院', '计算机应用技术', '2025级', '1班'],
        organizationText: '河南工业和信息化职业学院,计算机应用技术,2025级,1班',
        lastLogin: '2025-03-02 22:33'
      },
      {
        id: 2,
        name: '张婷',
        gender: '男',
        stuId: '20252154522',
        account: 'lisi002',
        password: '123456',
        contact: '-',
        organization: ['河南工业和信息化职业学院', '计算机应用技术', '2025级', '2班'],
        organizationText: '河南工业和信息化职业学院,计算机应用技术,2025级,2班',
        lastLogin: '2025-03-02 22:33'
      },
      {
        id: 3,
        name: '王浩然',
        gender: '男',
        stuId: '20252154523',
        account: 'wangwu003',
        password: '123456',
        contact: '-',
        organization: ['河南工业和信息化职业学院', '计算机应用技术', '2025级', '3班'],
        organizationText: '河南工业和信息化职业学院,计算机应用技术,2025级,3班',
        lastLogin: '2025-02-27 11:01'
      },
      {
        id: 4,
        name: '陈思宇',
        gender: '女',
        stuId: '20242154524',
        account: 'zhaoliu004',
        password: '123456',
        contact: '13110196219',
        organization: ['河南工业和信息化职业学院', '计算机应用技术', '2024级', '1班'],
        organizationText: '河南工业和信息化职业学院,计算机应用技术,2024级,1班',
        lastLogin: '2025-01-04 11:30'
      },
      {
        id: 5,
        name: '刘佳怡',
        gender: '女',
        stuId: '20242154525',
        account: 'sunqi005',
        password: '123456',
        contact: '13900000001',
        organization: ['河南工业和信息化职业学院', '计算机应用技术', '2024级', '2班'],
        organizationText: '河南工业和信息化职业学院,计算机应用技术,2024级,2班',
        lastLogin: '2025-03-05 09:10'
      },
      {
        id: 6,
        name: '赵阳',
        gender: '男',
        stuId: '20242154526',
        account: 'zhouba006',
        password: '123456',
        contact: '13800000002',
        organization: ['河南工业和信息化职业学院', '计算机应用技术', '2024级', '3班'],
        organizationText: '河南工业和信息化职业学院,计算机应用技术,2024级,3班',
        lastLogin: '2025-02-14 15:35'
      },
      {
        id: 7,
        name: '黄晓雯',
        gender: '男',
        stuId: '20232154527',
        account: 'wujiu007',
        password: '123456',
        contact: '-',
        organization: ['河南工业和信息化职业学院', '计算机应用技术', '2023级', '1班'],
        organizationText: '河南工业和信息化职业学院,计算机应用技术,2023级,1班',
        lastLogin: '2025-03-06 19:24'
      },
      {
        id: 8,
        name: '周子航',
        gender: '女',
        stuId: '20232154528',
        account: 'zhengshi008',
        password: '123456',
        contact: '13700000003',
        organization: ['河南工业和信息化职业学院', '计算机应用技术', '2023级', '2班'],
        organizationText: '河南工业和信息化职业学院,计算机应用技术,2023级,2班',
        lastLogin: '2025-04-24 14:18'
      },
      {
        id: 9,
        name: '孙磊',
        gender: '男',
        stuId: '20232154529',
        account: 'qianyi009',
        password: '123456',
        contact: '13600000004',
        organization: ['河南工业和信息化职业学院', '计算机应用技术', '2023级', '3班'],
        organizationText: '河南工业和信息化职业学院,计算机应用技术,2023级,3班',
        lastLogin: '2025-03-08 08:20'
      },
      {
        id: 10,
        name: '徐梦洁',
        gender: '女',
        stuId: '20222154530',
        account: 'suner010',
        password: '123456',
        contact: '13500000005',
        organization: ['河南工业和信息化职业学院', '计算机应用技术', '2022级', '1班'],
        organizationText: '河南工业和信息化职业学院,计算机应用技术,2022级,1班',
        lastLogin: '2025-01-12 10:00'
      }
    ]

const allUsers = ref(createMockUsers())
const filters = reactive({
  organization: undefined,
  name: '',
  gender: undefined,
  account: '',
  contact: '',
  loginStart: undefined,
  loginEnd: undefined
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})

// 显示的用户数据（经过搜索筛选后的数据）
const filteredUsers = ref([])

// 搜索状态
const isSearching = ref(false)

const pagedUsers = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  return filteredUsers.value.slice(start, start + pagination.pageSize)
})

function onPageChange(page) {
  pagination.currentPage = page
}

function onPageSizeChange(size) {
  pagination.pageSize = size
  pagination.currentPage = 1
}

function onQuery() {
  isSearching.value = true
  pagination.currentPage = 1

  // 执行搜索筛选
  let result = [...allUsers.value]

  // 姓名筛选
  if (filters.name) {
    result = result.filter(u => u.name.includes(filters.name))
  }

  // 性别筛选
  if (filters.gender) {
    result = result.filter(u => u.gender === filters.gender)
  }

  // 账号筛选
  if (filters.account) {
    result = result.filter(u => String(u.account).includes(filters.account))
  }

  // 联系方式筛选
  if (filters.contact) {
    result = result.filter(u => String(u.contact).includes(filters.contact))
  }

  // 组织结构筛选
  if (filters.organization && filters.organization.length) {
    // 将选择的组织结构数组转换为字符串，用于比较
    const selectedOrg = Array.isArray(filters.organization) ? filters.organization.join(',') : String(filters.organization)
    // 确保用户的组织结构包含选择的所有层级（前缀匹配）
    result = result.filter(u => {
      // 检查用户的组织结构文本是否以选择的组织结构开头
      return u.organizationText.startsWith(selectedOrg) ||
          // 或者用户的组织结构数组完全包含选择的组织结构数组
          (Array.isArray(filters.organization) &&
              filters.organization.every((level, index) => u.organization[index] === level))
    })
  }

  // 登录日期筛选
  if (filters.loginStart) {
    const start = new Date(filters.loginStart).getTime()
    result = result.filter(u => new Date(u.lastLogin).getTime() >= start)
  }

  if (filters.loginEnd) {
    const end = new Date(filters.loginEnd).getTime()
    result = result.filter(u => new Date(u.lastLogin).getTime() <= end)
  }

  // 更新显示数据
  filteredUsers.value = result

  ElMessage.success(`搜索完成，找到 ${result.length} 条记录`)
}

function onReset() {
  // 重置所有筛选条件
  filters.organization = undefined
  filters.name = ''
  filters.gender = undefined
  filters.account = ''
  filters.contact = ''
  filters.loginStart = undefined
  filters.loginEnd = undefined

  // 重置分页
  pagination.currentPage = 1

  // 更新状态和显示数据
  isSearching.value = false
  filteredUsers.value = [...allUsers.value]

  // 显示成功提示
  ElMessage.success('已重置搜索条件')
}

function onProfile(row) {
  router.push('/profile')
}


// 前往档案页面
function goToUserProfile() {
  navStore.addNav({ name: '档案', path: '/profile' })
  router.push('/profile')
}

// 初始化显示数据
function initDisplayData() {
  filteredUsers.value = [...allUsers.value]
}

// 页面加载时初始化
initDisplayData()
</script>

<template xmlns="http://www.w3.org/1999/html">
  <div class="users-container">
    <div class="filters">
      <div class="filters-row">
        <el-cascader
            v-model="filters.organization"
            :options="organizationOptions"
            placeholder="组织结构"
            clearable
            style="width: 260px"
        />

        <el-input v-model="filters.name" placeholder="输入姓名" clearable style="width: 260px" />
        <el-select v-model="filters.gender" placeholder="选择性别" clearable style="width: 260px">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </div>
      <div class="filters-row">
        <el-input v-model="filters.account" placeholder="输入账号" clearable style="width: 260px" />
        <el-input v-model="filters.contact" placeholder="输入联系方式" clearable style="width: 260px" />
      </div>
      <div class="filters-row">
        <el-button type="primary" :icon="Search" @click="onQuery">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </div>
    </div>
    <el-table :data="pagedUsers" stripe style="width: 100%" height="350" :header-cell-style="{ 'background-color': '#f5f7fa' }">
      <el-table-column type="index" label="序号" width="70" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="90" />
      <el-table-column prop="account" label="账号" width="160" />
      <el-table-column prop="organizationText" label="组织结构" min-width="240" show-overflow-tooltip />
      <el-table-column prop="lastLogin" label="上次登录" width="180" />
      <el-table-column label="操作" fixed="right" width="100">
        <template #default="scope">
          <el-button type="primary" link @click="goToUserProfile()">查看档案</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.pageSize"
          :current-page="pagination.currentPage"
          :total="filteredUsers.length"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
      />
    </div>


  </div>

</template>

<style lang="scss" scoped>
.users-container {
  background: #fff;
  border-radius: 8px;
  padding: 16px 16px 8px 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
}


.filters {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px 0 4px 0;
  border-top: 1px dashed #f0f0f0;
  border-bottom: 1px dashed #f0f0f0;
  margin-bottom: 12px;
}

.filters-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 12px 0 4px 0;
}
</style>

